const configuration = require("../utils/configuration");
const { vertifyToken, decryptToken } = require("../utils/setToken");

const checkLogin = async (ctx, next) => {
  //登录或退出
  //确定需要检查的
  const whiteList = configuration.whitelist;
  if (!whiteList.includes(ctx.url)) {
    const { authorization } = ctx.headers;
    //验证token黑名单
    const tokenIndex = global.blackTokenList.indexOf(authorization);
    //验证token
    if (!vertifyToken(authorization)) {
      //把token从黑名单移除掉
      global.blackTokenList.splice(tokenIndex, 1);
      return ctx.tokenExpires("无效token，请重新登录");
    } else {
      //黑名单，退出后的token
      if (tokenIndex !== -1) return ctx.tokenExpires("token失效，请重新登录");

      //获取解密后的用户信息
      const user = decryptToken(authorization).user;
      //解析token,存储到ctx.state,他是本次共享数据
      ctx.state.user = user;
    }
  }

  await next();
};

module.exports = checkLogin;
